package com.ztom.top100;

import java.util.HashMap;
import java.util.Map;

/**
 * 打家劫舍3
 * <p>
 * https://leetcode-cn.com/problems/house-robber-iii/
 *
 * @author ZhangTao
 */
public class Code81Rob {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int rob1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Map<TreeNode, Integer> selected = new HashMap<>();
        Map<TreeNode, Integer> unselected = new HashMap<>();
        dfs1(root, selected, unselected);
        return Math.max(selected.getOrDefault(root, 0), unselected.getOrDefault(root, 0));
    }

    private void dfs1(TreeNode node, Map<TreeNode, Integer> selected, Map<TreeNode, Integer> unselected) {
        if (node == null) {
            return;
        }
        dfs1(node.left, selected, unselected);
        dfs1(node.right, selected, unselected);
        // 选中当前节点: 则左右孩子不可选
        selected.put(node, node.val + unselected.getOrDefault(node.left, 0) + unselected.getOrDefault(node.right, 0));
        // 不选当前节点
        unselected.put(node,
                Math.max(selected.getOrDefault(node.left, 0), unselected.getOrDefault(node.left, 0))
                        + Math.max(selected.getOrDefault(node.right, 0), unselected.getOrDefault(node.right, 0))
        );
    }


    public int rob(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int[] info = dfs(root);
        // info[0]=选中; info[1]=不选
        return Math.max(info[0], info[1]);
    }

    private int[] dfs(TreeNode node) {
        if (node == null) {
            return new int[]{0, 0};
        }
        int[] l = dfs(node.left);
        int[] r = dfs(node.right);
        // 选中当前节点
        int selected = node.val + l[1] + r[1];
        // 不选当前节点
        int unselected = Math.max(l[0], l[1]) + Math.max(r[0], r[1]);
        return new int[] {selected, unselected};
    }
}
